package com.hnas.ecard.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hnas.common.domain.GetBalanceForm;
import com.hnas.common.util.CommonUtils;
import com.hnas.common.util.PostConnServerUtils;
import com.hnas.ecard.dao.AccECardDAO;
import com.hnas.ecard.dao.CardOptLogDAO;
import com.hnas.ecard.dao.CardTrailDAO;
import com.hnas.ecard.domain.BusinessType;
import com.hnas.ecard.domain.CardMarkConstant;
import com.hnas.ecard.domain.ECardCommonFinalValue;
import com.hnas.ecard.domain.ECardStatus;
import com.hnas.ecard.domain.ReturnECardMapper;
import com.hnas.ecard.orm.AccECard;
import com.hnas.ecard.orm.CardOptLog;
import com.hnas.ecard.orm.CardTrail;
import com.hnas.ecard.service.CardTrailService;

@Component("cardTrailService")
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class CardTrailServiceImpl implements CardTrailService {
	
	private static Logger logger = LoggerFactory.getLogger(CardTrailServiceImpl.class);

	@Autowired
	private AccECardDAO accECardDAO;
	@Autowired
	private CardTrailDAO cardTrailDAO;
	@Autowired
	private CardOptLogDAO cardOptLogDAO;
	
	@Value("#{component['subCode']}") // 发卡类型
	private String subCode;
	
	@Autowired
	private PostConnServerUtils postConnServerUtils;
	@Override
	public JSONObject findECardsByStatus(String accId, String phoneNo, String searchStatus, Integer pageNo, Integer pageSize) throws Exception {
		JSONObject result = new JSONObject();
		List<CardTrail> list = cardTrailDAO.findCardTrailByStatus(accId, phoneNo, searchStatus, pageNo, pageSize);
		if(null != list && list.size() > 0){
			JSONArray array = new JSONArray();
			JSONObject temp = null;
			GetBalanceForm getBalanceForm = null;
			for(CardTrail eCard : list){
				temp = new JSONObject();
				getBalanceForm = new GetBalanceForm();
				getBalanceForm.setCardNo(eCard.getSendCardNo());
				getBalanceForm.setSubCode(subCode);
				temp.put(ECardCommonFinalValue.card_no, eCard.getSendCardNo());
				temp.put(ECardCommonFinalValue.card_mark, "");
				temp.put(ECardCommonFinalValue.status, ReturnECardMapper.getReturnECardStatus(searchStatus, eCard.getStatus()));
				temp.put(ECardCommonFinalValue.face_value, "");
				temp.put(ECardCommonFinalValue.expiry_date, "");
				temp.put(ECardCommonFinalValue.send_phone_no, eCard.getSendPhoneNo());
				temp.put(ECardCommonFinalValue.send_name, eCard.getSendName());
				temp.put(ECardCommonFinalValue.send_msg, eCard.getSendMsg());
				temp.put(ECardCommonFinalValue.receive_phone_no, eCard.getReceivePhoneNo());
				temp.put(ECardCommonFinalValue.receive_name, eCard.getReceiveName());
				temp.put(ECardCommonFinalValue.remark, eCard.getRemark());
				temp.put(ECardCommonFinalValue.balance, postConnServerUtils.getBalance(getBalanceForm));
				array.add(temp);
			}
			result.put(ECardCommonFinalValue.ecard_list, array);
		}
		return result;
	}
	
	@Override
	public CardTrail saveOrUpdate(CardTrail vo) throws Exception {
		return cardTrailDAO.saveOrUpdate(vo);
	}

	@Override
	public List<CardTrail> findCardsByStatus(String accId, String phoneNo,String status) {
		return cardTrailDAO.findCardsByStatus(accId, phoneNo, status);
	}

	@Override
	public List<CardTrail> listOverTime() {
		return cardTrailDAO.listOverTime();
	}

	@Override
	public void autoReturnECard(CardTrail t) {
		try {
			String createType = String.valueOf(t.getCreateType());
			if (ECardCommonFinalValue.SALE_FOR_OTHER.equals(createType)) {//判断赠卡类型，如果是买给他人，则退回时需要绑定给赠卡人
				cardTrailDAO.autoReturnECardSaleForOther(t.getId());
				AccECard vo = new AccECard(CommonUtils.getUUID(), t.getSendAccId(), t.getSendCardNo(), Long.valueOf(t.getCurrentBalance()), null, CardMarkConstant.ELEC_CARD, null, ECardStatus.NORMAL, "购卡给他人的卡过期自动退回");
				vo.setIsDeleted(false);
				this.accECardDAO.saveOrUpdate(vo);
			}else {
				AccECard searchAccECard = new AccECard();
				searchAccECard.setCardNo(t.getSendCardNo());
				searchAccECard.setStatus(ECardStatus.GIVING);
				List<AccECard> list = this.accECardDAO.searchECardSql(searchAccECard);
				if(null == list || list.size() < 1) {
					logger.info("过期自动回退电子卡:无该电子卡的账户绑定记录");
					return;
				}
				AccECard accECard = list.get(0);
				cardTrailDAO.autoReturnECard(accECard.getId(),t.getId());
			}
			
			CardOptLog cardOptLog = new CardOptLog();
			cardOptLog.setId(CommonUtils.getUUID());
			cardOptLog.setAccId(t.getSendAccId());
			cardOptLog.setCardNo(t.getSendCardNo());
			cardOptLog.setReqParam(null);
			cardOptLog.setDealStatus(0);
			cardOptLog.setBusinessType(BusinessType.autoReturnECard);
			cardOptLog.setRemark(BusinessType.getBusinessTypeString(BusinessType.autoReturnECard));
			cardOptLog.setDealMsg("过期自动回退电子卡成功");
			this.cardOptLogDAO.saveOrUpdate(cardOptLog);
		}catch(Exception e) {
			logger.info("过期自动回退电子卡异常："+e.getMessage()+"-"+t.getId());
			e.printStackTrace();
		}
	}

	@Override
	public List<CardTrail> listByCardAndDate(String cardNo, String date) {
		return this.cardTrailDAO.listByCardAndDate(cardNo,date);
	}
}
